const express = require('express');
const process = require('process');
const bodyParser = require('body-parser');
const expressJwt = require('express-jwt')
const CONSTANT = require('./common/constant')

const morgan = require('morgan');
const path = require('path');
const fs = require('fs')
const fileStreamRotator = require('file-stream-rotator')

app = express();

var logDirectory = path.join(__dirname, 'log')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)

// create a rotating write stream
var accessLogStream = fileStreamRotator.getStream({
  date_format: 'YYYYMMDD',
  filename: path.join(logDirectory, '%DATE%.log'),
  frequency: 'daily',
  verbose: false
})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

port = process.env.PORT || 3000;
app.listen(port);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(expressJwt({
  secret: CONSTANT.SECRET_KEY
}).unless({
  path: ['/login', '/signup']  
}))

app.use(function (err, req, res, next) {
  //console.error(err);
  if (err.status === 401) {   
    res.status(401).send('invalid token')
  }
})

var routes = require('./api/routes/todoListRoutes');  
routes(app);

routes = require('./api/routes/loginRoutes');  
routes(app);

app.use(function (req, res) {
  res.status(404).send({ url: req.originalUrl + ' not found' })
});

console.log('todo list RESTful API server started on: ' + port);